import axios from 'axios';
import { ElMessage } from 'element-plus'
import config from '../config'

const http = axios.create({
  timeout: 10000
});

const token = window.sessionStorage.getItem('token')
if (token) {
  http.defaults.headers.common['Authorization'] = token;
} else {
  console.error('CSRF token not found');
}

http.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
http.defaults.baseURL = config.apiUrl

http.interceptors.response.use(
  response => {
    return response.data;
  },
  error => {

    if (!error['response']) {
      return Promise.reject(error)
    }
    switch (error.response.status) {
      case 400:
        ElMessage.error(error.response.data.error || '请求失败');
        break
      case 403:
        ElMessage.error(error.response.data.message || '您没有此操作权限！');
        break
      case 401:
        ElMessage.error(error.response.data.message || '您没有此操作权限！');
        break
      case 500:
      case 501:
      case 503:
      default:
        ElMessage.error('服务器出了点小问题，程序员小哥哥要被扣工资了~！');
    }
    return Promise.reject(error.response);
  }
);

export default http;
